<template>
    <div class="container-box">
        <el-row class="top-box" >
            <el-col class="title math-or-english-text">{{title}}</el-col>
            <el-col class="describe-box">
                <el-row class="describe"><span class="math-or-english-text">{{describe}}</span></el-row>
                <span class="type" v-if="type">[多选]</span>
                <span class="type" v-else>[单选]</span>
                <span class="type" v-if="anonymous">[非匿名投票]</span>
                <span class="type" v-else>[匿名投票]</span>
            </el-col>
        </el-row>

        <el-row class="middle-box">
            <!-- 单选时显示 -->
            <template v-if="!type">
                <el-col class="vote-item" v-for="(item,index) in iconList" :key="index">
                    <el-row>
                        <el-col class="left" :span="12">
                            <el-radio v-model="radio" :label="item.id" class="math-or-english-text">{{item.content}}</el-radio>
                        </el-col>
                        <el-col class="right" :span="12">
                            <span>{{item.number}}票</span>
                            <span>{{getPercentage(allVoteNumber,item.number)}}%</span>
                        </el-col>
                    </el-row>
                </el-col>
            </template>

            <!-- 多选时显示 -->
            <template v-else>
                <el-col class="vote-item" v-for="(item,index) in iconList" :key="index">
                    <el-row>
                        <el-col class="left" :span="12">
                            <label :for="item.id" class="math-or-english-text">
                                <input type="checkbox" v-model="checkList" name="" :id="item.id" :value="item.id">{{item.content}}
                            </label>
                        </el-col>
                        <el-col class="right" :span="12">
                            <span>{{item.number}}票</span>
                            <span>{{getPercentage(allVoteNumber,item.number)}}%</span>
                        </el-col>
                    </el-row>
                </el-col>

            </template>
        </el-row>
        <el-row class="footer-box">
            <el-col class="stop-time">截止日期: {{stopTime}}</el-col>
            <el-col v-if="flagVote" ><el-button @click="submit" type="primary" >确认投票</el-button></el-col>
        </el-row>
        
    <el-tooltip class="item" effect="dark" content="主页" placement="bottom">
        <span @click="$router.push('/home')" class="home-icon el-icon-s-home"></span>
    </el-tooltip>
    </div>
</template>

<script type="text/ecmascript-6">
    import { defineComponent,ref,onUnmounted,computed } from "vue";
    import { useRouter,useRoute } from 'vue-router'
    import { apiVoteDetail,apiToVote,apiToNoAnonymousVote } from '../api/index'
    import { ElMessage } from 'element-plus'
    export default defineComponent({
      name:"VoteDetail",
      setup(){
        const router = useRouter()
        const route = useRoute()

        //判断是否已投票
        let flagVote = ref(true)

        let vote_id = route.params.id
        //读取不到唯一值
        if ( !vote_id){
            router.replace('/login')
            return
        }

        let radio = ref(null)
        //多选时
        const checkList = ref([])

        let title = ref('')
        let describe = ref('')
        let iconList = ref([])
        let stopTime = ref('')
        let type = ref(0)
        let anonymous = ref(0)
        
        //获取投票信息
        getVoteDetail(vote_id)
        async function getVoteDetail(vote_id){
            const result = await apiVoteDetail(vote_id)
            if ( result.err_code == 200 ){
                title.value = result.data.title
                describe.value = result.data.describe
                iconList.value = result.data.option
                stopTime.value = result.data.end_time
                type.value = result.data.type *1 
                anonymous.value = result.data.anonymous *1
                return
            }
            ElMessage.error(result.message);
        }


        //计算总的票数
        let allVoteNumber = computed(()=>{
            return iconList.value.reduce((pre,item)=>{
                return pre+item.number
            },0)
        })
        //计算百分比
        function getPercentage(allVoteNumber,currentVoteNumber){
            //总数为0 直接返回
                console.log('执行了',allVoteNumber,currentVoteNumber)
            if ( !allVoteNumber) {
                return 0.0.toFixed(1)
            }
            console.log('执行； ',allVoteNumber,currentVoteNumber)
            let percentageNum = (100/allVoteNumber) * currentVoteNumber
            return percentageNum.toFixed(1)
        }

        
        async function submit(){
            //校验数据不通过
            if ( !verify() ) return
            let userId = JSON.parse(window.sessionStorage.getItem('info'))
            let result
            //匿名投票且未登录
            if ( !anonymous.value && !userId ){
                //true为多选，false为单选
                type.value ? result = await apiToVote(checkList.value,null,type.value) : result = await apiToVote(radio.value,null,type.value)
            }else if( anonymous.value && !userId){
                //非匿名投票且没有登录
                 ElMessage.error("请先登录");
                 //保存投票项id
                 window.localStorage.setItem('v',vote_id)
                 router.push('/login')
                 return
            }else{
                //匿名投票但有登录 或 非匿名投票但登录
                type.value ? result = await apiToNoAnonymousVote(checkList.value,userId.id,type.value) : result = await apiToVote(radio.value,userId.id,type.value)
            }
            

            if ( result.err_code == 200 ){
                ElMessage.success({
                    message: result.message,
                    type: 'success'
                });
                radio.value = null
                checkList.value = []
                getVoteDetail(vote_id)
                flagVote.value = false
                return
            }
            radio.value = null
            checkList.value = []
            ElMessage.error(result.message);
        }
        //校验数据
        function verify(){
            if ( new Date( stopTime ) <  new Date( new Date() )  ){
                ElMessage.error('该投票已截止');
                return
            }
            if ( type.value && checkList.value.length == 0){
                ElMessage.error('至少选择一个投票项');
                return
            }
            if ( !type.value && !radio.value){
                ElMessage.error('请选择投票项');
                return
            }
            return true
        }

        //清除session
        onUnmounted(()=>{
            window.sessionStorage.removeItem('v')
        })

        return {
            title,
            describe,
            iconList,
            stopTime,
            type,
            anonymous,
            radio,
            checkList,
            allVoteNumber,
            getPercentage,
            submit,
            flagVote
        }
      },
  })
</script>

<style scoped lang="less" >
@color:#0B9CE9;
//纯数字或英文，让其自动换行
.math-or-english-text{
    width: 100%;
    word-wrap: break-word;
}
//返回主页的icon
.home-icon{
    position: absolute;
    top: 5px;
    left: 3vw;
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    font-size: 20px;
    color: @color;
    cursor: pointer;
}
.container-box{
    position: relative;
    padding: 6vh 4vw 2vh;
    min-height: 92vh;
    box-sizing: content-box;
    // background: url("../../public/images/staff_1024.jpg") no-repeat;
    // background-image: -webkit-linear-gradient(331deg, #e6ebec 0%, #4da2f7 50%, #acf5f9 10%);
    background-image: -webkit-linear-gradient(331deg, #7eeecf 0%, #8ce8ec 50%, #95eef3 10%);
    // background-image: -webkit-linear-gradient(-22deg, #00aeef 0%, #4da2f7 50%, #205dbf 10%);
    .top-box{
        margin-bottom: 2vh;
        .title{
            padding-bottom: 2vh;
            border-bottom: 1px solid #eee;
            font-size: 20px;
            font-weight: 600;
        }
        .describe-box{
            margin: 5px 0px;
            .describe{
                padding-bottom: 2vh;
                border-bottom: 1px solid #eee;
            }
            .type{
                margin: 10px 0px;
                margin-right: 10px;
                color: #409EFF;
            }
        }

    }
    .middle-box{
        width: 100%;
       .vote-item{
           margin-bottom: 2vh;
           padding: 10px;
           border: 1px solid #eee;
           border-radius: 5px;
           .left{
               input{
                   margin-right: 8px;
               }
           }
           .right{
               font-size: 14px;
               text-align: right;
               span{
                   margin-right:20px;
               }
           }
       }
    }
    .footer-box{
        margin: 2vh 0px;
        width: 100%;
        text-align: center;
        .stop-time{

            color: #999;
            margin: 5vh 0px;
        }
        .el-button{
            width: 80%;
        }
    }
}
.left /deep/ .el-radio__label{
    white-space: pre-wrap;
}
</style>
